package com.yanwq.sayhi.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.yanwq.sayhi.R;
import com.yanwq.sayhi.widget.MProgressDialog;

import butterknife.ButterKnife;

/**
 * 作者：yanweiqiang。
 * 日期：2016/2/2 14:27。
 */
public abstract class BaseFragment extends Fragment {
    private MProgressDialog mPD;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPD = new MProgressDialog(getActivity());

        if (getView() != null) {
            getView().setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
        }

        ButterKnife.bind(this, view);

        init();
        initView();
    }

    public abstract void init();

    public abstract void initView();

    public View findViewById(int id) {
        if (getView() != null) {
            return getView().findViewById(id);
        }

        throw new NullPointerException("Fragment root view is null!");
    }

    public void showProgressDialog(String message) {
        mPD.setMessage(message);
        mPD.show();
    }

    public void cancelProgressDialog() {
        mPD.cancel();
    }

    public void post(Runnable runnable) {
        if (getView() != null) {
            getView().post(runnable);
        } else {
            throw new NullPointerException("Fragment root view is null!");
        }
    }

    public void post(Runnable runnable, int delayMillis) {
        if (getView() != null) {
            getView().postDelayed(runnable, delayMillis);
        } else {
            throw new NullPointerException("Fragment root view is null!");
        }
    }

    public void popBackStack() {
        getActivity().getSupportFragmentManager().popBackStack();
    }
}
